/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jxta;

import exclusionmutua.ExclusionMutua;
import java.util.Enumeration;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.discovery.DiscoveryService;
import net.jxta.document.Advertisement;
import net.jxta.pipe.PipeService;
import net.jxta.protocol.DiscoveryResponseMsg;
import net.jxta.protocol.PipeAdvertisement;
import utilidades.ConsultaAdvertisement;
/**
 *
 * @author kastillo
 */
public class EscucharConsultas implements DiscoveryListener, Runnable{
    private static DiscoveryService discovery;
    private long waittime;
    private int tipoAdv;
    private String peerId;
    private String nombreAtt;
    private String valorAtt;
    private int cantResp;
//    private RecibidorAdv recibidor;
    private int tmpTotalEspera;
    private PipeService pipeService;
    private static boolean debeContinuar;
    private final PipeAdvertisement pipedeDescarga;
    private  Map<String, ExclusionMutua> exclusionMutuaMap;
    private PipeAdvertisement pipeEM;
    private final String nombrePeer;

    public EscucharConsultas(DiscoveryService discovery2,
            PipeService pipeService,
            PipeAdvertisement pipedeDescarga,
            Map<String, ExclusionMutua> exclusionMutuaMap,
            PipeAdvertisement pipeEM,
            String nombrePeer ) {
       this.pipeEM = pipeEM;
       //para escuchar
        discovery = discovery2;

       //para responder
       this.pipeService = pipeService;
       this.pipedeDescarga = pipedeDescarga;
       this.exclusionMutuaMap = exclusionMutuaMap;
       this.nombrePeer = nombrePeer;
       
       //parametros para escuchar
        this.waittime = 5 * 1000L;
        this.peerId = null;
        this.tipoAdv = DiscoveryService.ADV;
        this.nombreAtt = ConsultaAdvertisement.queryTag;
        this.valorAtt = "*";
        this.cantResp = 50; // cantidad maxima de escucha advertiment por cada par
        this.tmpTotalEspera = Integer.MAX_VALUE;
    }

    public void run() {
        empezar();
    }

    private void empezar() {
         long tmpTermino = System.currentTimeMillis() + tmpTotalEspera;
         debeContinuar = true;
           // Add ourselves as a DiscoveryListener for DiscoveryResponse events
            discovery.addDiscoveryListener(this);

            while (debeContinuar) {
                // wait a bit before sending a discovery message
                System.out.println("Escuchando Consultas");
                // look for any peer
                discovery.getRemoteAdvertisements(
                        // no specific peer (propagate)
                        peerId,
                        // Adv type
                        tipoAdv,
                        // Attribute = name
                        nombreAtt,
                        // Value = the tutorial
                        valorAtt,
                        // one advertisement response is all we are looking for
                        cantResp);

            try {
                System.out.println("Sleeping for :" + waittime);
                Thread.sleep(waittime);
            } catch (InterruptedException ex) {
                Logger.getLogger(EscucharConsultas.class.getName()).log(Level.INFO,  "Solicitud de terminar el proceso", ex);
            }
                long tmpActual = System.currentTimeMillis();
                if(tmpActual >= tmpTermino)
                    debeContinuar = false;
            }

    }
  public void discoveryEvent(DiscoveryEvent ev) {
        DiscoveryResponseMsg res = ev.getResponse();

        // let's get the responding peer's advertisement
        System.out.println(" [  Got a Discovery Response [" + res.getResponseCount() + " elements]  from peer : " + ev.getSource() + "  ]");

        ConsultaAdvertisement adv;
        Enumeration en = res.getAdvertisements();

        if (en != null) {
            while (en.hasMoreElements()) {
                adv = (ConsultaAdvertisement) en.nextElement();
             System.out.println("Encontró Consulta");
             System.out.println(adv);
             ProcesarConsultas  procesarConsultas =
                     new ProcesarConsultas(pipeService,
                     adv.getPipe(),
                     pipedeDescarga,
                     exclusionMutuaMap,
                     pipeEM,
                     nombrePeer);

             System.out.println("peeeeeeeeeeeeeeeeeeeeeeeeeeeeeeer" + adv.pipeTag);
             procesarConsultas.manipularAdvertisement(adv);
             
            }
        }
    }

    void pararEscucha() {

        System.out.println("==================se detuvo la escucha=================");
        debeContinuar = false;
    }

}

